from django.conf import settings
from django.utils.deprecation import MiddlewareMixin
from django.core.cache import cache
from django.http import JsonResponse
import uuid
import json


def is_system_overloaded():
    # 替换为实际的负载检测逻辑
    return False


class QueueMiddleware(MiddlewareMixin):
    def process_request(self, request):
        # 检查路径是否在不可降级路径列表中
        if request.path in settings.NON_DEGRADABLE_PATHS:
            return None  # 继续正常流程

        if is_system_overloaded():
            # 当系统负载太高时，请求进入队列
            request_id = str(uuid.uuid4())
            request_data = {
                'path': request.path,
                'method': request.method,
            }
            # 存储到 Redis 队列，在“request_queue”键下
            cache.lpush('request_queue', json.dumps(request_data))

            return JsonResponse(
                {'message': 'Your request is being processed and will be completed shortly. Please wait.'}, status=202)

        return None

    @staticmethod
    def process_queued_requests():
        # 处理 Redis 队列中的请求
        while cache.llen('request_queue') > 0:
            _, data = cache.lpop('request_queue')
            data = json.loads(data)
            # 这里添加处理逻辑，例如调用内部服务或者使用任务队列处理
            print(f"Processing data from queue: {data}")